package com.css.fxfzypg.modules.maps.controller;

import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.maps.queryParams.MapQueryParams;
import com.css.fxfzypg.modules.maps.service.TaskRegionMapService;
import com.css.fxfzypg.modules.qhmapfiles.service.QhMapFilesService;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author zyt
 * @create 2023-1-5
 * 根据任务查询行政区划信息
 */
@RestController
@RequestMapping("/taskRegionQuery")
@Slf4j
public class TaskRegionController {

    @Resource
    TaskRegionMapService taskRegionMapService;//地图使用

    @Autowired
    private QhMapFilesService qhMapFilesService;//文件管理

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 根据任务表类型、任务ID，查询行政区划--省|市|区县的名称和code列表
     */
    @GetMapping("/queryProvinceCityCountyNameCodeListByTaskId/{type}/{taskId}")
    public RestResponse queryProvinceCityCountyNameCodeListByTaskId(@PathVariable("type") String type,@PathVariable("taskId") String taskId){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.queryProvinceCityCountyNameCodeListByTaskId(type,taskId));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据任务表类型、任务ID，查询行政区划--省|市|区县|乡镇的名称和code列表
     */
    @GetMapping("/queryProvinceCityCountyStreetNameCodeListByTaskId/{type}/{taskId}")
    public RestResponse queryProvinceCityCountyStreetNameCodeListByTaskId(@PathVariable("type") String type,@PathVariable("taskId") String taskId){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.queryProvinceCityCountyStreetNameCodeListByTaskId(type,taskId));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据经纬度，查询行政区划--省|市|区县的名称和code列表
     */
    @PostMapping("/queryProvinceCityCountyNameCodeListByLonLat")
    public RestResponse queryProvinceCityCountyNameCodeListByLonLat(@RequestBody Map<String,String> map){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.queryProvinceCityCountyNameCodeListByLonLat(map.get("lon"),map.get("lat")));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据地图圈选区域，查询行政区划--省|市|区县的名称和code列表
     */
    @PostMapping("/queryProvinceCityCountyNameCodeListByGeomText")
    public RestResponse queryProvinceCityCountyNameCodeListByGeomText(@RequestBody Map<String,String> map){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.queryProvinceCityCountyNameCodeListByGeomText(map.get("geomText")));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据地图圈选区域，查询行政区划--省|市|区县|乡镇的名称和code列表
     */
    @PostMapping("/queryProvinceCityCountyStreetNameCodeListByGeomText")
    public RestResponse queryProvinceCityCountyStreetNameCodeListByGeomText(@RequestBody Map<String,String> map){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.queryProvinceCityCountyStreetNameCodeListByGeomText(map.get("geomText")));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据任务ID、烈度、（区县|乡镇）统计人员死亡数
     */
    @GetMapping("/countPbeInjuries")
    public RestResponse countPbeInjuries(@RequestParam("taskId") String taskId,@RequestParam("dzIntensity") String dzIntensity,@RequestParam("qcType") String qcType){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.countPbeInjuries(taskId,dzIntensity,qcType));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据任务ID、烈度、（区县|乡镇）统计经济损失（万元）
     */
    @GetMapping("/countPbeLosses")
    public RestResponse countPbeLosses(@RequestParam("taskId") String taskId,@RequestParam("dzIntensity") String dzIntensity,@RequestParam("qcType") String qcType){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.countPbeLosses(taskId,dzIntensity,qcType));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 根据任务ID、烈度、（区县|乡镇）统计需紧急安置人数
     */
    @GetMapping("/countPbePlant")
    public RestResponse countPbePlant(@RequestParam("taskId") String taskId,@RequestParam("dzIntensity") String dzIntensity,@RequestParam("qcType") String qcType){

        RestResponse restResponse = null;
        try{
            restResponse = RestResponse.succeed(taskRegionMapService.countPbePlant(taskId,dzIntensity,qcType));
        }catch (Exception e){
            log.error("查询数据失败!",e);
            restResponse = RestResponse.fail("查询数据失败");
        }
        return restResponse;
    }

    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadDistrictBoundaryFiles")
    public RestResponse uploadSpaceData(@RequestParam("files") MultipartFile[] files, MapQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        String province = queryParams.getProvince(), city = queryParams.getCity(), area = queryParams.getArea();
        //if ("".equals(province) ) return RestResponse.fail("请选择场地所在省份!");
        //if ("".equals(city)) return RestResponse.fail("请选择场地所在城市!");
        //if ("".equals(area)) return RestResponse.fail("请选择场地所在区县!");

        //判断是否已上传未保存文件--上传类型（行政区划_）
        int fileCount = qhMapFilesService.lookUpMapFiles("0","行政区划_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件等待数据入库, 若要上传最新数据请稍后在【管理】功能中删除数据.");

        //判断是否已上传正在保存文件--上传类型（行政区划_）
        fileCount = qhMapFilesService.lookUpMapFiles("2","行政区划_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传文件数据正在入库, 若要上传最新数据请稍后在【管理】功能中删除数据.");

        //判断是否已存在上传数据--上传类型（行政区划_）
        fileCount = qhMapFilesService.lookUpMapFiles("1","行政区划_","1",province,city,area);
        if(fileCount>0) return RestResponse.succeed("【" + province + "-" + city + "-" + area + "】已上传数据, 若要上传最新数据请先在【管理】功能中删除数据.");

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String gdbFileName = "";//gdb文件名
        String jxfilename = "";//shp文件名
        String dbffilename = "";
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        //判断是否为GDB文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            if (oldFileName.equals("gdb")) {//是否存在gdb文件
                String fName = "新建文件地理数据库";
                String postfix = ".gdb";
                String prefix = "行政区划_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                gdbFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                break;
            }
        }

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
                newFileName = gdbFileName + "/"+oldFileName;
            }else {//SHP文件
                // 上传后文件名
                String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
                String prefix = "行政区划_";
                String district = (province == null ? "0" : province) + "_" + (city == null ? "0" : city) + "_" + (area == null ? "0" : area);
                newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
                if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                    jxfilename = newFileName;
                }
                if (oldFileName.contains(".dbf") && oldFileName.endsWith(".dbf")) {
                    dbffilename = newFileName;
                }
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                //file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            //returnMsg.append(oldFileName);
            //returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename+gdbFileName);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        if(!PlatformObjectUtils.isEmpty(gdbFileName)) {//GDB文件
            resultMsg = gdbFileName;//返回GDB文件名
            System.out.println(new Date()+"-----------3.开始importGDBFile");
            //resMsg = qhRiskLevelMapService.checkGDBFiles(uploadPath + gdbFileName, province, city, area);
            System.out.println(new Date()+"-----------4.结束importGDBFile");
            if (resMsg.indexOf("spatialReferenceError") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据.");
        }else{//SHP文件
            System.out.println(new Date()+"-----------3.开始importShapeFile");
            resMsg = taskRegionMapService.checkSHPFiles(uploadPath + jxfilename, province, city, area, formatDate, userID);
            System.out.println(new Date()+"-----------4.结束importShapeFile");
        }
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "字段值存在空值, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    /**
     * 批量上传文件.shp、.prj
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadShpFile")
    public RestResponse uploadShpFile(@RequestParam("files") MultipartFile[] files) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String jxfilename = "";//shp文件名
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        String currTime = System.currentTimeMillis() + "";

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            // 上传后文件名
            String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
            String prefix = "导入任务区域_";
            newFileName = prefix + "_" + fName + "_" + formatDate + "_" + currTime + postfix;
            if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                jxfilename = newFileName;
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                //file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            //returnMsg.append(oldFileName);
            //returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        //SHP文件
        System.out.println(new Date()+"-----------3.开始importShapeFile");
        resMsg = taskRegionMapService.checkSHPFiles1(uploadPath + jxfilename);
        System.out.println(new Date()+"-----------4.结束importShapeFile");
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功.");
        }else{
            System.out.println(new Date()+"-----------5.上传失败.");
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed(resMsg.split("#")[0] + "字段值存在空值, 请对照字段说明检查数据的正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        if (resMsg.indexOf("geomTypeError") != -1) return RestResponse.succeed("上传文件不是面数据, 请检查数据的正确性.");
        if (resMsg.indexOf("多条空间数据") != -1) return RestResponse.succeed("上传文件中包含多条空间数据，请融合为1条数据后再导入.");
        if (resMsg.indexOf("空间数据自相交") != -1) return RestResponse.succeed("空间数据存在自相交，请处理后再导入.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    /**
     * 上传文件.txt
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadTxtFile")
    public RestResponse uploadTxtFile(@RequestParam("files") MultipartFile[] files) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String jxfilename = "";//shp文件名
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());
        String currTime = System.currentTimeMillis() + "";

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            // 上传后文件名
            String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
            String prefix = "导入任务区域_";
            newFileName = prefix + "_" + fName + "_" + formatDate + "_" + currTime + postfix;
            if (newFileName.contains(".txt") && newFileName.endsWith(".txt")) {
                jxfilename = newFileName;
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                File _file = new File(uploadPath + newFileName);
                FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                //file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            //returnMsg.append(oldFileName);
            //returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        //txt文件
        System.out.println(new Date()+"-----------3.开始importTxtFile");
        resMsg = taskRegionMapService.checkTxtFiles(uploadPath + jxfilename);
        System.out.println(new Date()+"-----------4.结束importTxtFile");
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功.");
        }else{
            System.out.println(new Date()+"-----------5.上传失败.");
        }
        if (resMsg.indexOf("geomTypeError") != -1) return RestResponse.succeed("上传文件内容的经纬度不能组成面数据, 请对照模板检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    //下载模板
    @PostMapping(value = "/downloadTxt", produces = "text/html;charset=UTF-8")
    public void downloadTxt(String fileName, HttpServletResponse response) {
        log.info("入参: 模板名全称", fileName);
        try {
            //请求头的模板名为中文
            String file_name = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("content-Type", "text/plain");
            response.setHeader("Content-disposition", "attachment;fileName=" + file_name);
//            response.setContentType("application/x-download");
            //获取文件
            //File file =  ResourceUtils.getFile("classpath:excel/"+fileName);
            File file = ResourceUtils.getFile("/usr/zhaoshuai/ypg/excel" + "/" + fileName);
            FileInputStream inputStream = new FileInputStream(file);
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[65536];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            log.info(fileName + ": 模板下载完成");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(fileName + ":" + e);
        }
    }
}
